/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.pipeparser.util;

import java.io.Reader;
import java.util.Map;
import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import java.util.LinkedList;

/**
 *
 * @author carlos
 */
public class Pipe {
    private JSONParser parser = new JSONParser();
    private Map wkgPipe; //The working pipe
    private ContainerFactory containerFactory = new ContainerFactoryImpl();
    
    public Pipe(String pipeDefinition){
        
        try{

            Map pipeDef = (Map)parser.parse(pipeDefinition, containerFactory);
            
            //Lets get the elements for the pipe (subelements of the attribute "working"
            //of the JSON of the pipe
            this.wkgPipe = getWorkingPipe(pipeDef);
            
        }catch(Exception e){

            e.printStackTrace();
            
        }

    }

    public Pipe(Reader pipeDefinition){

        try{

            Map pipeDef = (Map)parser.parse(pipeDefinition, containerFactory);

            //Lets get the elements for the pipe (subelements of the attribute "working"
            //of the JSON of the pipe
            this.wkgPipe = getWorkingPipe(pipeDef);

        }catch(Exception e){

            e.printStackTrace();

        }

    }

    private Map getWorkingPipe(Map pipeDef){

        Map query = (Map)pipeDef.get("query");
        Map results = (Map)query.get("results");
        Map json = (Map)results.get("json");
        Map pipe = (Map)json.get("PIPE");

        return (Map)pipe.get("working");
        
    }

    public LinkedList getModules(){

        return (LinkedList)wkgPipe.get("modules");

    }

    public LinkedList getWires(){

        LinkedList ll = null;

        if(wkgPipe.get("wires") instanceof LinkedList){
            ll = (LinkedList)wkgPipe.get("wires");
        }else{
            ll = new LinkedList();
            ll.add(wkgPipe.get("wires"));
        }
            
        return ll;
        
    }

    public LinkedList getTerminalData(){

        return (LinkedList)wkgPipe.get("terminaldata");

    }

    public LinkedList getLayout(){

        return (LinkedList)wkgPipe.get("layout");

    }

}
